<?php declare(strict_types=1);

namespace Distributed\Pool;

use Swoole\Coroutine\Channel;
use Redis;

/**
 * redis 链接池
 * @author mg
 *
 */
class RedisPool
{
	/**
	 * @var Channel
	 */
	protected $pool;
	
	/**
	 * RedisPool constructor.
	 * @param int $size 连接池的尺寸
	 */
	function __construct(int $size = 3)
	{
		$this->pool = new Channel($size);
		for ($i = 0; $i < $size; $i++)
		{
			$redis = new Redis();
			$res = $redis->connect('127.0.0.1', 6379);
			if ($res == false)
			{
				throw new \RuntimeException("failed to connect redis server.");
			}
			else
			{
				$this->put($redis);
			}
		}
	}
	
	function put(Redis $redis): void
	{
		$this->pool->push($redis);
	}
	
	function get(): Redis
	{
		return $this->pool->pop();
	}
	
	public function release(): void
	{
		$this->pool->close();
	}
}